/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ctrl;

import carte.CarteTruand;
import java.util.ArrayList;
import java.util.Random;
import perso.Agent;
import perso.Chef;
import perso.Personnage;
import perso.Truand;

/**
 *
 * @author Vincent
 */
public class FactoryTruand extends AbstractFactory {

    private CarteTruand carte;
    public staticObj[][] planques;

    public CarteTruand createMap(int width, int height, int nbPlanques) {
        Personnage[][] posPerso = new Personnage[width][height];
        planques = new staticObj[width][height];
        for (int i = 0; i < nbPlanques; i++) {
            addPlanqueInMap();
        }
        carte = CarteTruand.getInstance(posPerso, planques);
        return carte;
    }

    public ArrayList<Personnage> populateWorld(int nbrAgents, int nbrTruands) {
        ArrayList<Personnage> listPerso = new ArrayList<>();
        Chef c = Chef.getInstance(nbrPerso++, carte);
        addPersoInMap(c);
        listPerso.add(c);

        for (int a = 0; a < nbrAgents; a++) {
            Agent agent = new Agent(nbrPerso++, carte);
            addPersoInMap(agent);
            listPerso.add(agent);
        }
        for (int a = 0; a < nbrTruands; a++) {

            Truand truand = new Truand(nbrPerso++, carte, getRandomBoolean());
            addPersoInMap(truand);
            listPerso.add(truand);
        }
        return listPerso;
    }

    private void addPersoInMap(Personnage perso) {
        int w = carte.getPerso().length;
        int h = carte.getPerso()[0].length;
        if (nbrPerso >= (w * h)) {
            System.err.println("La carte est pleine");
        }
        boolean freePos = false;
        Random r = new Random();
        while (!freePos) {
            int rx = r.nextInt(w);
            int ry = r.nextInt(h);
            if (carte.getPerso()[rx][ry] == null) {
                if (perso instanceof Agent) {
                    if(planques[rx][ry]==staticObj.PLANQUE){
                        continue;
                    }
                }
                freePos = true;
                carte.getPerso()[rx][ry] = perso;
                perso.px = rx;
                perso.py = ry;

            }
        }
    }

    private void addPlanqueInMap() {
        int w = planques.length;
        int h = planques[0].length;

        boolean freePos = false;
        Random r = new Random();
        while (!freePos) {
            int rx = r.nextInt(w);
            int ry = r.nextInt(h);
            if (planques[rx][ry] == null) {
                freePos = true;
                planques[rx][ry] = staticObj.PLANQUE;
            }
        }
    }


}
